import {
  _decorator,
  Component,
  ScrollView,
  instantiate,
  Node,
  Prefab,
  log,
  math,
  UITransform,
} from "cc";
import { itemLabel } from "./itemLabel";
const { ccclass, property } = _decorator;

// 1、定义全局变量，存储当前已经发起的请求次数和需要请求的次数(真实场景变量应该定义在class中)
let requestCount: number = 0; // 请求次数
let loadCount: number = 1; // 加载数据次数，初始为1，因为必定请求一次接口的
// 模拟接口返回
const mock = {
  list: [],
  pageSize: 10,
  total: 100,
};
@ccclass("ScrollView")
export class Scroll extends Component {
  // 获取ScrollView组件
  @property(ScrollView) scroll: ScrollView = null;
  // 获取预制体item
  @property(Prefab) itemPrefab: Prefab = null;

  protected onLoad(): void {
    requestCount = Math.ceil(mock.total / mock.pageSize); // 向上取整，需要请求次数

    // this.getList();
  }

  protected update(dt: number): void {
    // 2、获取滚动距离，判断是否触底，触底就发送请求
    // const scrollView = this.node.getComponent(ScrollView); // 获取ScrollView组件

    // const maxScrollOffset = scrollView.getMaxScrollOffset().y; // 最大滚动偏移量
    // const scrollOffset = scrollView.getScrollOffset().y; // 当前滚动偏移量

    // // 如果没有加载完数据，并且触底，就加载数据
    // if (loadCount < requestCount && maxScrollOffset === Math.floor(scrollOffset)) {
    //   log(loadCount, requestCount, maxScrollOffset, Math.floor(scrollOffset));

    //   // 发送请求
    //   this.getList();
    // }
    // if (loadCount == 4) {
    //   log(loadCount, requestCount, maxScrollOffset, Math.floor(scrollOffset));
    // }
  }

  // 3、渲染列表
  async getList() {
    // 3.1: 发送请求
    // const { list, total } = await request();

    let list = [];
    // 3.3：拼接数据
    for (let i = 0; i < mock.pageSize; ++i) {
      list.push(i);
    }
    mock.list = [...mock.list, ...list];

    // 3.4: 渲染滚动列表内容
    this.renderList(loadCount - 1);
    // 3.2: 请求发送成功，loadCount++
    loadCount += 1;
  }

  renderList(loadCount) {
    // ...省略加载预设体等一堆逻辑
    const scrollView = this.node.getComponent(ScrollView); // 获取ScrollView组件
    const UI = scrollView.content.getComponent(UITransform); // 获取ScrollView组件

    UI.height = mock.list.length * 50;

    for (let i = loadCount * mock.pageSize; i < mock.list.length; i++) {
      // 克隆并将节点添加到content中
      let itemNode: Node = instantiate(this.itemPrefab);
      if (itemNode) {
        let pos = new math.Vec3(0, -i * 50, 0);
        itemNode.setPosition(pos);
        itemNode.parent = scrollView.content;
        // this.scrollView.content.addChild(itemNode);
        (itemNode.getComponent("itemLabel") as itemLabel).init(i * 50, i);
      }
    }
  }
}
